package bb.lanxing.lib.devices.bryton.bbcp;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
//import com.alipay.sdk.util.e;
import bb.lanxing.lib.devices.bryton.nordic.dfu.AbortedException;
import bb.lanxing.lib.devices.bryton.nordic.dfu.DeviceDisconnectedException;
import bb.lanxing.lib.devices.bryton.nordic.dfu.DfuException;
import bb.lanxing.lib.devices.bryton.nordic.dfu.HexFileValidationException;
import bb.lanxing.lib.devices.bryton.nordic.dfu.HexInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@SuppressLint("MissingPermission")
public class DfuManager extends BleManager {
    public static final String BROADCAST_ERROR = "com.brytonsport.dfu.BROADCAST_ERROR";
    public static final String BROADCAST_PROGRESS = "com.brytonsport.dfu.BROADCAST_PROGRESS";
    public static final int DFU_STATUS_CRC_ERROR = 5;
    public static final int DFU_STATUS_DATA_SIZE_EXCEEDS_LIMIT = 4;
    public static final int DFU_STATUS_INVALID_STATE = 2;
    public static final int DFU_STATUS_NOT_SUPPORTED = 3;
    public static final int DFU_STATUS_OPERATION_FAILED = 6;
    public static final int DFU_STATUS_SUCCESS = 1;
    public static final String EXTRA_DEVICE_ADDRESS = "com.brytonsport.dfu.EXTRA_DEVICE_ADDRESS";
    public static final String EXTRA_DEVICE_NAME = "com.brytonsport.dfu.EXTRA_DEVICE_NAME";
    public static final String EXTRA_FILE_PATH = "com.brytonsport.dfu.EXTRA_FILE_PATH";
    public static final String EXTRA_FILE_URI = "com.brytonsport.dfu.EXTRA_FILE_URI";
    public static final String EXTRA_LOG_URI = "com.brytonsport.dfu.EXTRA_LOG_URI";
    private static final int MAX_PACKET_SIZE = 20;
    private static final int OP_CODE_PACKET_RECEIPT_NOTIF_KEY = 17;
    private static final int OP_CODE_PACKET_RECEIPT_NOTIF_REQ_KEY = 8;
    private static final int OP_CODE_RECEIVE_ACTIVATE_AND_RESET_KEY = 5;
    private static final int OP_CODE_RECEIVE_FIRMWARE_IMAGE_KEY = 3;
    private static final int OP_CODE_RECEIVE_RESET_KEY = 6;
    private static final int OP_CODE_RECEIVE_START_DFU_KEY = 1;
    private static final int OP_CODE_RECEIVE_VALIDATE_KEY = 4;
    private static final int OP_CODE_RESPONSE_CODE_KEY = 16;
    public static final String PREFS_DFU_IN_PROGRESS = "com.brytonsport.dfu.PREFS_DFU_IN_PROGRESS";
    private int mBytesConfirmed;
    private int mBytesSent;
    private DfuManagerCallbacks mCallbacks;
    private HexInputStream mHexInputStream;
    private int mImageSizeInBytes;
    private int mImageSizeInPackets;
    private boolean mImageSizeSent;
    private boolean mNotificationsEnabled;
    private int mPacketsSendSinceNotification;
    private boolean mRequestCompleted;
    public static final UUID DFU_SERVICE_UUID = new UUID(23296205844446L, 1523193452336828707L);
    private static final UUID DFU_CONTROL_POINT_UUID = new UUID(23300500811742L, 1523193452336828707L);
    private static final UUID DFU_PACKET_UUID = new UUID(23304795779038L, 1523193452336828707L);
    private static final UUID CLIENT_CHARACTERISTIC_CONFIG = new UUID(45088566677504L, -9223371485494954757L);
    private static final byte[] OP_CODE_START_DFU = {1};
    private static final byte[] OP_CODE_RECEIVE_FIRMWARE_IMAGE = {3};
    private static final byte[] OP_CODE_VALIDATE = {4};
    private static final byte[] OP_CODE_ACTIVATE_AND_RESET = {5};
    private static final byte[] OP_CODE_RESET = {6};
    private static final byte[] OP_CODE_PACKET_RECEIPT_NOTIF_REQ = {8, 0, 0};
    private byte[] mReceivedData = null;
    private int mPacketsBeforeNotification = 10;
    private byte[] mBuffer = new byte[20];
    private int mLastProgress = -1;
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DfuManager.BROADCAST_PROGRESS.equals(action)) {
                DfuManager.this.mCallbacks.onProgressUpdate(intent.getIntExtra("com.brytonsport.bbcp.EXTRA_DATA", 0));
            } else if (!DfuManager.BROADCAST_ERROR.equals(action)) {
            } else {
                DfuManager.this.mCallbacks.onUploaded(intent.getIntExtra("com.brytonsport.bbcp.EXTRA_DATA", 0));
            }
        }
    };
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt bluetoothGatt, int i, int i2) {
            if (i != 0) {
                DfuManager dfuManager = DfuManager.this;
                dfuManager.loge("Connection state change error: " + i + " newState: " + i2);
                DfuManager.this.mErrorState = i | 1024;
            } else if (i2 == 2) {
                DfuManager.this.logi("Connected to GATT server");
                DfuManager.this.mConnectionState = -2;
                boolean discoverServices = bluetoothGatt.discoverServices();
                DfuManager dfuManager2 = DfuManager.this;
                StringBuilder sb = new StringBuilder();
                sb.append("Attempting to start service discovery...");
                sb.append(discoverServices ? "succeed" : "failed"/*e.b*/);
                dfuManager2.logi(sb.toString());
                if (discoverServices) {
                    return;
                }
                DfuManager.this.mErrorState = -261;
            } else if (i2 == 0) {
                DfuManager.this.logi("Disconnected from GATT server");
                DfuManager.this.mConnectionState = 0;
            }
            synchronized (DfuManager.this.mLock) {
                DfuManager.this.mLock.notifyAll();
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
            if (i == 0) {
                DfuManager.this.logi("Services discovered");
                DfuManager.this.mConnectionState = -3;
            } else {
                DfuManager dfuManager = DfuManager.this;
                dfuManager.loge("Service discovery error: " + i);
                DfuManager.this.mErrorState = i | 1024;
            }
            synchronized (DfuManager.this.mLock) {
                DfuManager.this.mLock.notifyAll();
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt bluetoothGatt, BluetoothGattDescriptor bluetoothGattDescriptor, int i) {
            if (i == 0) {
                if (DfuManager.CLIENT_CHARACTERISTIC_CONFIG.equals(bluetoothGattDescriptor.getUuid())) {
                    DfuManager dfuManager = DfuManager.this;
                    dfuManager.logi("descriptor value=" + BleManager.toHexString(bluetoothGattDescriptor.getValue()));
                    DfuManager dfuManager2 = DfuManager.this;
                    boolean z = false;
                    if (bluetoothGattDescriptor.getValue()[0] == 1) {
                        z = true;
                    }
                    dfuManager2.mNotificationsEnabled = z;
                }
            } else {
                DfuManager dfuManager3 = DfuManager.this;
                dfuManager3.loge("Descriptor write error: " + i);
                DfuManager.this.mErrorState = i | 1024;
            }
            synchronized (DfuManager.this.mLock) {
                DfuManager.this.mLock.notifyAll();
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i) {
            if (i == 0) {
                boolean z = true;
                if (DfuManager.DFU_PACKET_UUID.equals(bluetoothGattCharacteristic.getUuid())) {
                    if (!DfuManager.this.mImageSizeSent) {
                        DfuManager.this.mImageSizeSent = true;
                    } else {
                        DfuManager.access$512(DfuManager.this, bluetoothGattCharacteristic.getValue().length);
                        DfuManager.access$608(DfuManager.this);
                        boolean z2 = DfuManager.this.mPacketsBeforeNotification > 0 && DfuManager.this.mPacketsSendSinceNotification == DfuManager.this.mPacketsBeforeNotification;
                        if (DfuManager.this.mBytesSent != DfuManager.this.mImageSizeInBytes) {
                            z = false;
                        }
                        if (z2 || z) {
                            return;
                        }
                        try {
                            if (!DfuManager.this.mAborted) {
                                byte[] bArr = DfuManager.this.mBuffer;
                                DfuManager.this.writePacket(bluetoothGatt, bluetoothGattCharacteristic, bArr, DfuManager.this.mHexInputStream.readPacket(bArr));
                                DfuManager.this.updateProgressNotification();
                                return;
                            }
                            synchronized (DfuManager.this.mLock) {
                                DfuManager.this.mLock.notifyAll();
                            }
                            return;
                        } catch (HexFileValidationException unused) {
                            DfuManager.this.loge("Invalid HEX file");
                            DfuManager.this.mErrorState = 259;
                        } catch (IOException e) {
                            DfuManager.this.loge("Error while reading the input stream", e);
                            DfuManager.this.mErrorState = 260;
                        }
                    }
                } else {
                    DfuManager.this.mRequestCompleted = true;
                }
            } else {
                DfuManager dfuManager = DfuManager.this;
                dfuManager.loge("Characteristic write error: " + i);
                DfuManager.this.mErrorState = i | 1024;
            }
            synchronized (DfuManager.this.mLock) {
                DfuManager.this.mLock.notifyAll();
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
            if (bluetoothGattCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0) == 17) {
                BluetoothGattCharacteristic characteristic = bluetoothGatt.getService(DfuManager.DFU_SERVICE_UUID).getCharacteristic(DfuManager.DFU_PACKET_UUID);
                try {
                    DfuManager.this.mBytesConfirmed = bluetoothGattCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 1);
                    DfuManager.this.mPacketsSendSinceNotification = 0;
                    if (!DfuManager.this.mAborted) {
                        byte[] bArr = DfuManager.this.mBuffer;
                        DfuManager.this.writePacket(bluetoothGatt, characteristic, bArr, DfuManager.this.mHexInputStream.readPacket(bArr));
                        DfuManager.this.updateProgressNotification();
                        return;
                    }
                } catch (HexFileValidationException unused) {
                    DfuManager.this.loge("Invalid HEX file");
                    DfuManager.this.mErrorState = 259;
                } catch (IOException e) {
                    DfuManager.this.loge("Error while reading the input stream", e);
                    DfuManager.this.mErrorState = 260;
                }
            } else {
                DfuManager.this.mReceivedData = bluetoothGattCharacteristic.getValue();
            }
            synchronized (DfuManager.this.mLock) {
                DfuManager.this.mLock.notifyAll();
            }
        }
    };

    static /* synthetic */ int access$512(DfuManager dfuManager, int i) {
        int i2 = dfuManager.mBytesSent + i;
        dfuManager.mBytesSent = i2;
        return i2;
    }

    static /* synthetic */ int access$608(DfuManager dfuManager) {
        int i = dfuManager.mPacketsSendSinceNotification;
        dfuManager.mPacketsSendSinceNotification = i + 1;
        return i;
    }

    public DfuManager() {
        this.TAG = "DfuManager";
    }

    public int getConnectionState() {
        return this.mConnectionState;
    }

    public void connect(Context context, BluetoothDevice bluetoothDevice) {
        try {
            _connect(context, bluetoothDevice, this.mGattCallback, this.mReceiver);
        } catch (AbortedException e) {
            e.printStackTrace();
        } catch (DeviceDisconnectedException e2) {
            e2.printStackTrace();
        }
    }

    public void setGattCallbacks(DfuManagerCallbacks dfuManagerCallbacks, Context context) {
        this.mCallbacks = dfuManagerCallbacks;
        this.mContext = context;
        LocalBroadcastManager.getInstance(context).registerReceiver(this.mReceiver, makeIntentFilter());
    }

    public void uploadFirmware(java.lang.String r19, android.net.Uri r20) {
        /*
            Method dump skipped, instructions count: 797
            To view this dump add '--comments-level debug' option
        */
        throw new UnsupportedOperationException("Method not decompiled: ");
    }

    private HexInputStream openInputStream(Uri uri) throws FileNotFoundException, IOException {
        return new HexInputStream(this.mContext.getContentResolver().openInputStream(uri));
    }

    private HexInputStream openInputStream(String str) throws FileNotFoundException, IOException {
        return new HexInputStream(new FileInputStream(str));
    }

    private void setCharacteristicNotification(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, boolean z) throws DeviceDisconnectedException, DfuException, AbortedException {
        this.mErrorState = 0;
        StringBuilder sb = new StringBuilder();
        sb.append(z ? "Enabling " : "Disabling");
        sb.append(" notifications...");
        logi(sb.toString());
        bluetoothGatt.setCharacteristicNotification(bluetoothGattCharacteristic, z);
        logi("ENABLE_NOTIFICATION_VALUE=" + toHexString(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));
        BluetoothGattDescriptor descriptor = bluetoothGattCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
        descriptor.setValue(z ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        bluetoothGatt.writeDescriptor(descriptor);
        try {
            synchronized (this.mLock) {
                while (this.mNotificationsEnabled != z && this.mConnectionState == -3 && this.mErrorState == 0 && !this.mAborted) {
                    this.mLock.wait();
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
        if (this.mAborted) {
            throw new AbortedException();
        }
        if (this.mErrorState != 0) {
            throw new DfuException("Unable to set notifications state", this.mErrorState);
        }
        if (this.mConnectionState != -3) {
            throw new DeviceDisconnectedException("Unable to set notifications state", this.mConnectionState);
        }
    }

    private void writeOpCode(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, byte[] bArr) throws DeviceDisconnectedException, DfuException, AbortedException {
        this.mReceivedData = null;
        this.mErrorState = 0;
        this.mRequestCompleted = false;
        bluetoothGattCharacteristic.setValue(bArr);
        bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
        try {
            synchronized (this.mLock) {
                while (!this.mRequestCompleted && this.mConnectionState == -3 && this.mErrorState == 0 && !this.mAborted) {
                    this.mLock.wait();
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
        if (this.mAborted) {
            throw new AbortedException();
        }
        if (this.mErrorState != 0) {
            throw new DfuException("Unable to write Op Code " + ((int) bArr[0]), this.mErrorState);
        } else if (this.mConnectionState != -3) {
            throw new DeviceDisconnectedException("Unable to write Op Code " + ((int) bArr[0]), this.mConnectionState);
        }
    }

    private void writeImageSize(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i) throws DeviceDisconnectedException, DfuException, AbortedException {
        this.mReceivedData = null;
        this.mErrorState = 0;
        this.mImageSizeSent = false;
        bluetoothGattCharacteristic.setWriteType(1);
        bluetoothGattCharacteristic.setValue(i, 20, 0);
        bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
        try {
            synchronized (this.mLock) {
                while (!this.mImageSizeSent && this.mConnectionState == -3 && this.mErrorState == 0 && !this.mAborted) {
                    this.mLock.wait();
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
        if (this.mAborted) {
            throw new AbortedException();
        }
        if (this.mErrorState != 0) {
            throw new DfuException("Unable to write Image Size", this.mErrorState);
        }
        if (this.mConnectionState != -3) {
            throw new DeviceDisconnectedException("Unable to write Image Size", this.mConnectionState);
        }
    }

    private byte[] readNotificationResponse() throws DeviceDisconnectedException, DfuException, AbortedException {
        this.mErrorState = 0;
        try {
            synchronized (this.mLock) {
                while (this.mReceivedData == null && this.mConnectionState == -3 && this.mErrorState == 0 && !this.mAborted) {
                    this.mLock.wait();
                }
            }
        } catch (InterruptedException e) {
            loge("Sleeping interrupted", e);
        }
        if (this.mAborted) {
            throw new AbortedException();
        }
        if (this.mErrorState != 0) {
            throw new DfuException("Unable to write Op Code", this.mErrorState);
        }
        if (this.mConnectionState != -3) {
            throw new DeviceDisconnectedException("Unable to write Op Code", this.mConnectionState);
        }
        return this.mReceivedData;
    }

    private void setNumberOfPackets(byte[] bArr, int i) {
        bArr[1] = (byte) (i & 255);
        bArr[2] = (byte) ((i >> 8) & 255);
    }

    public void updateProgressNotification() {
        int i = (int) ((this.mBytesSent * 100.0f) / this.mImageSizeInBytes);
        if (this.mLastProgress == i) {
            return;
        }
        this.mLastProgress = i;
        sendProgressBroadcast(i, BROADCAST_PROGRESS);
    }

    private byte[] uploadFirmwareImage(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, HexInputStream hexInputStream) throws DeviceDisconnectedException, DfuException, AbortedException {
        this.mReceivedData = null;
        this.mErrorState = 0;
        byte[] bArr = this.mBuffer;
        try {
            writePacket(bluetoothGatt, bluetoothGattCharacteristic, bArr, hexInputStream.readPacket(bArr));
            try {
                synchronized (this.mLock) {
                    while (this.mReceivedData == null && this.mConnectionState == -3 && this.mErrorState == 0 && !this.mAborted) {
                        this.mLock.wait();
                    }
                }
            } catch (InterruptedException e) {
                loge("Sleeping interrupted", e);
            }
            if (this.mAborted) {
                throw new AbortedException();
            }
            if (this.mErrorState != 0) {
                throw new DfuException("Uploading Fimrware Image failed", this.mErrorState);
            }
            if (this.mConnectionState != -3) {
                throw new DeviceDisconnectedException("Uploading Fimrware Image failed: device disconnected", this.mConnectionState);
            }
            return this.mReceivedData;
        } catch (HexFileValidationException unused) {
            throw new DfuException("HEX file not valid", 259);
        } catch (IOException unused2) {
            throw new DfuException("Error while reading file", 260);
        }
    }

    public void writePacket(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, byte[] bArr, int i) {
        if (bArr.length != i) {
            byte[] bArr2 = new byte[i];
            System.arraycopy(bArr, 0, bArr2, 0, i);
            bArr = bArr2;
        }
        bluetoothGattCharacteristic.setValue(bArr);
        bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
    }

    @Override
    protected void terminateConnection(BluetoothGatt bluetoothGatt, int i) {
        logi("terminateConnection");
        if (this.mConnectionState != 0) {
            try {
                BluetoothGattService service = bluetoothGatt.getService(DFU_SERVICE_UUID);
                if (service != null) {
                    setCharacteristicNotification(bluetoothGatt, service.getCharacteristic(DFU_CONTROL_POINT_UUID), false);
                }
            } catch (Exception unused) {
                unused.printStackTrace();
            }
            disconnect();
        }
        closeBluetoothGatt();
    }

    private IntentFilter makeIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BROADCAST_PROGRESS);
        intentFilter.addAction(BROADCAST_ERROR);
        return intentFilter;
    }

    public void close() {
        if (this.mContext != null) {
            LocalBroadcastManager.getInstance(this.mContext).unregisterReceiver(this.mReceiver);
        }
    }
}
